package com.vanysoft.business.kpi.controller;

import com.baomidou.mybatisplus.enums.SqlLike;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.vanysoft.business.data.entity.CategoryList;
import com.vanysoft.business.data.service.CategoryListService;
import com.vanysoft.business.kpi.cache.LocalCache;
import com.vanysoft.business.kpi.entity.KpiItem;
import com.vanysoft.business.kpi.entity.KpiItemRule;
import com.vanysoft.business.kpi.service.KpiItemRuleService;
import com.vanysoft.business.kpi.service.KpiItemService;
import com.vanysoft.business.sys.entity.UserInfo;
import com.vanysoft.common.utils.Excel.EasyPoiUtil;
import com.vanysoft.framework.aop.VanySoftValidationException;
import com.vanysoft.framework.base.action.BaseController;
import com.vanysoft.framework.config.mvc.SessionUser;
import com.vanysoft.framework.result.ResponseUtil;
import com.vanysoft.framework.utils.JSONResponse;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.util.DoubleSummaryStatistics;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * KPI规则处理类
 *
 * @author yu_chen
 * @date 2018-07-09 14:22
 **/

@Controller
@RequestMapping("kpi/rule")
public class KpiRuleController extends BaseController {

    private final Log log = LogFactory.getLog(getClass());

    @Autowired
    private KpiItemRuleService kpiItemRuleService;

    @Autowired
    private KpiItemService kpiItemService;

    @Autowired
    private CategoryListService categoryListService;

    /**
     * 跳转到KPIRule界面
     */
    @RequestMapping("index")
    public String toKpiRule() {

        return "kpi/rule";
    }

    /**
     * 按品类查询所有的数据
     *
     * @param ruleScope 品类
     * @param kpiItemId 条目
     * @param family    考核域
     * @return 返回json数据
     */
    @RequestMapping("query/page")
    @ResponseBody
    public JSONResponse selectAllTableData(Page<KpiItemRule> page, String ruleScope, String kpiItemId, String family) {
        //查询所有的考核项
        Page<KpiItemRule> kpiItemRulePage = kpiItemRuleService.selectPage(page, new EntityWrapper<KpiItemRule>()
                .eq(StringUtils.isNotEmpty(ruleScope), "rule_scope", ruleScope)
                .eq(StringUtils.isNotEmpty(kpiItemId), "kpi_item_id", kpiItemId)
                .like(StringUtils.isNotEmpty(family), "kpi_item_id", family, SqlLike.RIGHT)
                .eq("is_valid", "Y")
        );
        initKpiItemRule(kpiItemRulePage.getRecords());
        return new JSONResponse(kpiItemRulePage);
    }

    /**
     * 查询搜索数据
     *
     * @return 搜索数据
     */
    @ResponseBody
    @RequestMapping("/query/search/data")
    public JSONResponse selectSearchData() {
        Map<String, Object> searchData = new HashMap<>();
        List<CategoryList> categoryLists = categoryListService.selectList(new EntityWrapper<CategoryList>()
                .eq("IS_ENABLE", 1)
                .eq("CURRENT_LEVEL", "Category"));
        List<String> familyList = kpiItemService.selectAllFamily();
        List<KpiItem> kpiItems = kpiItemService.selectList(null);
        searchData.put("familyList", familyList);
        searchData.put("categoryList", categoryLists);
        searchData.put("kpiItemList", kpiItems);
        return ResponseUtil.success(searchData);
    }

    /**
     * 导入数据 并进行校验
     *
     * @param file 上传的文件
     * @return 是否导入成功
     */
    @ResponseBody
    @RequestMapping("import")
    public JSONResponse importKpiRule(MultipartFile file, @SessionUser UserInfo userInfo) {
        Map<String, KpiItem> kpiItemMap = kpiItemService.selectMapKpiItem();
        List<KpiItemRule> kpiItemRules = EasyPoiUtil.importExcel(file, 0, 1, KpiItemRule.class);

        if (kpiItemRules == null) {
            log.error("importKpiRule导入数据为空");
            throw new VanySoftValidationException(getMessage("error.kpi.excel.msg.empty-list"));
        }

        for (KpiItemRule kpiItemRule : kpiItemRules) {
            if (!kpiItemMap.containsKey(kpiItemRule.getKpiItemId())) {
                log.error(getMessage("error.kpi.excel.msg.item.not-exist", kpiItemRule.getId()));
                throw new VanySoftValidationException(getMessage("error.kpi.excel.msg.item.not-exist", kpiItemRule.getId()));
            }
        }
        //获取所有的分类 判断权重是是否等于1
        Map<String, DoubleSummaryStatistics> dataMap = kpiItemRules.stream()
                .collect(Collectors.groupingBy(KpiItemRule::getRuleScope, Collectors.summarizingDouble(KpiItemRule::getWeight)));
        for (String s : dataMap.keySet()) {
            double sum = dataMap.get(s).getSum();
            if (sum > 1) {
                log.error(getMessage("error.kpi.excel.msg.rule-scope.weight.below100", s));
                throw new VanySoftValidationException(getMessage("error.kpi.excel.msg.rule-scope.weight.below100", s));
            }
            if (sum < 1) {
                log.error(getMessage("error.kpi.excel.msg.rule-scope.weight.more100", s));
                throw new VanySoftValidationException(getMessage("error.kpi.excel.msg.rule-scope.weight.more100", s));
            }
        }
        //批量插入
        boolean isSuccess = kpiItemRuleService.insertAllKpiRule(kpiItemRules, userInfo.getUsername());

        return ResponseUtil.successOrFail(isSuccess);
    }

    /**
     * 导出excel
     */
    @RequestMapping("export/data")
    public void exportExcel(String ruleScope, String kpiItemId, String family) {
        List<KpiItemRule> kpiItemRules = kpiItemRuleService.selectList(new EntityWrapper<KpiItemRule>()
                .eq(StringUtils.isNotEmpty(ruleScope), "rule_scope", ruleScope)
                .eq(StringUtils.isNotEmpty(kpiItemId), "kpi_item_id", kpiItemId)
                .like(StringUtils.isNotEmpty(family), "kpi_item_id", family, SqlLike.RIGHT)
                .eq("is_valid", "Y")
        );
        initKpiItemRule(kpiItemRules);
        EasyPoiUtil.exportExcel(kpiItemRules, "", "sheet01", KpiItemRule.class, "kpiRuleExport.xlsx", getResponse());
    }


    /**
     * 导出模板
     */
    @RequestMapping("export/template")
    public void exportTemplate() {
        List<KpiItemRule> kpiItemRules = kpiItemRuleService.selectList(
                new EntityWrapper<KpiItemRule>().eq("is_valid", "Y")
        );
        initKpiItemRule(kpiItemRules);
        EasyPoiUtil.exportExcel(kpiItemRules, "", "sheet01", KpiItemRule.class, "kpiRuleTemplate.xlsx", false, getResponse());
    }

    /**
     * 初始化kpi规则
     *
     * @param kpiItemRules 关联查询
     */
    private void initKpiItemRule(List<KpiItemRule> kpiItemRules) {
        for (KpiItemRule kpiItemRule : kpiItemRules) {
            KpiItem kpiItem = kpiItemService.selectById(kpiItemRule.getKpiItemId());
            kpiItemRule.setWeightStr(String.valueOf(kpiItemRule.getWeight()) + "%");
            kpiItemRule.setItemType(LocalCache.MAP_CACHE.get(kpiItemRule.getItemType()));
            kpiItemRule.setKpiItemName(kpiItem.getKpiItemName());
            kpiItemRule.setFamily(kpiItem.getFamily());
            kpiItemRule.setKpiDes(kpiItem.getKpiDes());
        }
    }
}